# -*- coding: UTF-8 -*-
from django.shortcuts import redirect, render, render_to_response
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.db.models import Count
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.csrf import csrf_exempt, csrf_protect
import os

from .models import *
from .utilities import smart_paginator, page_guide, get_permissions, has_permission
import apis
from .conf_parser import get_confs
from templatetags.parseperm import parseperm_v2

#index - Default page
def index(request):
    tpl_vals = get_confs(request)

    posts = Topic.objects.order_by("-last_edited")[:20]
    boards = Board.objects.all()
    return render_to_response('forum/index/main.html', {'tpl_vals': tpl_vals, 'posts': posts, 'boards': boards}, context_instance=RequestContext(request))

#updated by author @ 2014/6/2
def message(request):
    tpl_vals = get_confs(request)

    return render_to_response('forum/message/main.html', {'tpl_vals': tpl_vals}, context_instance=RequestContext(request))

#board - list all titles of topics belong to a specific board
def board(request, tboard, page="1", test_perm='read'):
    tpl_vals = get_confs(request)
    page = int(page)
    perm_list = []

    try:
        tboard = Board.objects.get(name=tboard)
    except Board.DoesNotExist:
        return 'ok'
        return render_to_response(
                'forum/board/access_exceptions.html',
                {
                    'error_code': 1,
                    'board': tboard,
                    'request': request,
                    'tpl_vals': tpl_vals,
                    'perm_list': perm_list,
                    'test_perm': test_perm
                },
                context_instance=RequestContext(request)
                )

    perm_list = get_permissions(request, tboard)
    if not has_permission(request, tboard, test_perm, perm_list):
        return render_to_response(
                'forum/board/access_exceptions.html',
                {
                    'error_code': 2,
                    'board': tboard,
                    'request': request,
                    'tpl_vals': tpl_vals,
                    'perm_list': perm_list,
                    'test_perm': test_perm
                },
                context_instance=RequestContext(request)
                )

    posts = Topic.objects.filter(board=tboard).order_by("-post_time")
    paged_result = smart_paginator(posts, page=page, num=5)
    posts = paged_result['output']
    link_list = paged_result['link_list']
    return render_to_response('forum/board/main.html', {'perm_list': perm_list, 'tpl_vals': tpl_vals, 'current_page': page, 'posts': posts, 'link_list': link_list, 'board': tboard}, context_instance=RequestContext(request))

def single_post(request, id):
    tpl_vals = get_confs(request, 'post')
    id = int(id)

    try:
        post = Topic.objects.get(pk=id)
    except ObjectDoesNotExist:
        return board(request, '')

    perm_list = get_permissions(request, post.board)
    if not has_permission(request, post, 'read', perm_list):
        return board(request, post.board.name)

    return render_to_response('forum/post/single_post.html', {'board': post.board, 'perm_list': perm_list, 'tpl_vals': tpl_vals, 'post': post, 'is_single': True}, context_instance=RequestContext(request))

def topic(request, id, page = "1"):
    tpl_vals = get_confs(request, 'post')

    tree_node = int(id)
    page = int(page)

    posts = Topic.objects.filter(tree_node=tree_node).order_by("pk")

    if not posts:
        return HttpResponse(status=404)

    perm_list = get_permissions(request, posts.last().board)

    if not has_permission(request, posts.last(), 'read', perm_list):
        return board(request, posts.last().board.name)

    tboard = posts.last().board
    paged_results = smart_paginator(posts, page=page, num=5)
    posts = paged_results['output']
    link_list = paged_results['link_list']

    return render_to_response('forum/post/main.html', {'board': tboard, 'perm_list': perm_list, 'tpl_vals': tpl_vals, 'posts': posts, 'link_list': link_list, 'tree_node': tree_node, 'is_single': False, 'current_page': page}, context_instance=RequestContext(request))

def new_topic(request, tboard):
    tpl_vals = get_confs(request)

    try:
        tboard = Board.objects.get(name=tboard)
    except Board.DoesNotExist:
        return board(request, tboard)

    perm_list = get_permissions(request, tboard)
    if not has_permission(request, tboard, 'post', perm_list):
        return board(request, tboard.name, test_perm='post')

    if not request.method == 'POST':
        return render_to_response('forum/post/post_form.html', {'board': tboard, 'tpl_vals': tpl_vals}, context_instance=RequestContext(request))

    return apis.topic(request, "add", tboard, 0)

def reply(request, id):
    tpl_vals = get_confs(request)
    id = int(id)

    if request.method == 'POST':
        return apis.topic(request, 'reply', '', id)

    father_post = Topic.objects.get(pk=id)
    return render_to_response('forum/post/post_form.html', {'tpl_vals': tpl_vals, 'father_post': father_post, 'board': father_post.board}, context_instance=RequestContext(request))

#created by author @ 2014/6/23
def get_push(request, id):
    id = int(id)
    try:
        post = Topic.objects.get(pk=id)
    except Topic.DoesNotExist:
        return HttpResponse("")

    return render_to_response('forum/post/push_block.html', {'post': post}, context_instance=RequestContext(request))

def new_push(request, id):
    id = int(id)
    if apis.push(request, 'add', id):
        return get_push(request, id)
    else:
        return HttpResponse(status=200)

#created by author @ 2014/6/1
def delete_push(request, id):
    id = int(id)
    return apis.push(request, 'del', id)

#by author @ 2014/5/24 17:05
def edit_topic(request, id):
    tpl_vals = get_confs(request)
    id = int(id)

    if request.method == 'POST':
        return apis.topic(request, 'edit', '', id)

    try:
        post = Topic.objects.get(pk=id)
    except:
        #need a better error page
        return HttpResponse(status=400)

    return render_to_response('forum/post/post_form.html', {'tpl_vals': tpl_vals, 'origin_post': post, 'board': post.board}, context_instance=RequestContext(request))

#by author @ 2014/5/27 14:15
def delete_topic(request, id):
    tpl_vals = get_confs(request)
    id = int(id)

    return apis.topic(request, 'del', '', id)

#by author @ 2014/5/27 15:40
def member_operate(request, action=None):
    tpl_vals = get_confs(request)

    if request.method == 'POST':
        return apis.user(request, action)

    if action == 'login':
        return render_to_response('forum/user/login.html', {'tpl_vals': tpl_vals}, context_instance=RequestContext(request))
    elif action == 'register':
        return render_to_response('forum/user/register.html', {'tpl_vals': tpl_vals}, context_instance=RequestContext(request))
    elif action == 'logout':
        return apis.user(request, action)

#updated by author @ 2014/6/12
def manage(request, part=None):
    tpl_vals = get_confs(request)

    template_vars = {}
    template_vars['tpl_vals'] = tpl_vals
    if part == 'board':
        render_page = 'forum/manage/board/main.html'
        boards = Board.objects.all()
        categories = BoardCategory.objects.all()
        template_vars['boards'] = boards
        template_vars['categories'] = categories
    elif part == 'user':
        render_page = 'forum/manage/users/main.html'
        users = ForumUser.objects.all().annotate(Count('topic'))
        template_vars['users'] = users
    elif part == 'message':
        return message_manage(request, 'list', 0)
    elif part == None:
        render_page = 'forum/manage/main.html'

    return render_to_response(render_page,
                              template_vars,
                              context_instance=RequestContext(request))
#created by author @ 2014/6/1
def board_manage(request, action, id, perm_str='00000'):
    if not request.user.is_superuser:
        return HttpResponse("2")

    id = int(id)
    if request.method == 'POST':
        return apis.board(request, action, id)

#created by author @ 2014/6/1
def boardcategory_manage(request, action, id):
    if not request.user.is_superuser:
        return HttpResponse("2")

    id = int(id)
    if request.method == 'POST':
        return apis.board_category(request, action, id)

#created by author @ 2014/6/25
def board_manage_perm(request, id, perm_type, perm_str):
    #return a string same as displayed in admin panel(like "A.R.P")
    if not request.user.is_superuser:
        return HttpResponse("2")

    id = int(id)
    try:
        tboard = Board.objects.get(pk=id)
        new_perm_str = request.POST['perm_str']

        if perm_type == 'admin':
            tboard.admin_perm = new_perm_str
        elif perm_type == 'user':
            tboard.user_perm = new_perm_str
        elif perm_type == 'guest':
            tboard.anonymous_perm = new_perm_str

        tboard.save()
    except:
        return HttpResponse("1")
    else:
        return HttpResponse("0")

#updated by author @ 2014/6/12
def message_manage(request, action, id):
    if id == '':
        id = 0
    else:
        id = int(id)

    tpl_vals = get_confs(request)

    if request.method == 'POST':
        return apis.message(request, action, id)

    if action == 'create':
        return render_to_response('forum/manage/message/create.html', {'tpl_vals': tpl_vals}, context_instance=RequestContext(request))
    elif action == 'update':
        try:
            message = Message.objects.get(pk=id)
        except Message.DoseNotExist:
            return page_guide(request, to='referer')
        else:
            return render_to_response('forum/manage/message/create.html', {'tpl_vals': tpl_vals, 'message': message}, context_instance=RequestContext(request))
    elif action == 'list':
        messages = Message.objects.all()
        return render_to_response('forum/manage/message/list.html', {'tpl_vals': tpl_vals, 'messages': messages}, context_instance=RequestContext(request))

#created by author @ 2014/6/18
@ensure_csrf_cookie
def get_html(request, filename):
    html_snippets_dir = os.path.join(
            os.path.dirname(__file__),
            'templates/forum/html_snippets/'
            )
    snippet_path = os.path.join(
            html_snippets_dir,
            filename
            )
    if os.path.exists(snippet_path):
        return render_to_response(snippet_path, context_instance=RequestContext(request))
    else:
        return HttpResponse(status=404)

#created by author @ 2014/7/13
@csrf_exempt
def attachment(request, action):
    if not request.method == 'POST':
        return HttpResponse('2')

    if action == 'upload':
        uploaded_attachment = Attachment(file=request.FILES['attachment'])
        try:
            uploaded_attachment.save()
        except:
            return HttpResponse('1')
        else:
            return HttpResponse(
                    '<span id="current_id">{0}</span>'.format(uploaded_attachment.id)
                    +
                    """
                    <script>
                        var uploaded_ids = window.parent.parent.document.getElementById("uploaded_attachments");
                        var current_id = document.getElementById("current_id").innerHTML;
                        if(uploaded_ids.value == '') {
                            uploaded_ids.value += current_id;
                        } else {
                            uploaded_ids.value += ',' + current_id;
                        }
                    </script>
                    """
                    )
